package com.springboot.demo.enuml;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Stream;

public interface IBaseEnum<T> {
    default void initEnum(T code, String msg) {
        EnumContainer.putEnum(this, code, msg);
    }


    default T getCode(){
        return EnumContainer.getEnum(this).getCode();
    }

    default String getMsg(){
        return EnumContainer.getEnum(this).getText();
    }

    @SuppressWarnings("unchecked")
    static <T,R extends IBaseEnum<T>> R getByCode(Class<? extends IBaseEnum<T>> clazz, T code){

        R r = Stream.of(clazz.getEnumConstants())
                .filter(tEnumBean -> tEnumBean.getCode().equals(code))
                .map(v -> (R) v)
                .findAny()
                .orElse(null);
        String name = clazz.getSimpleName();
        System.out.println(name);
        System.out.println(r);
        return r;
    }

    class EnumContainer {
        private static final Map<IBaseEnum, EnumBean> ENUM_MAP = new ConcurrentHashMap<>();

        public static <T> void putEnum(IBaseEnum baseEnum, T code, String msg) {
            ENUM_MAP.put(baseEnum, new EnumBean(code, msg));
        }


        public static <K extends IBaseEnum<T>, T> EnumBean<T> getEnum(K dist) {
            return ENUM_MAP.get(dist);
        }

    }

    class EnumBean<T> {
        public EnumBean(T code, String text) {
            this.code = code;
            this.text = text;
        }

        private final T code;

        private final String text;

        @Override
        public String toString() {
            return "EnumBean{" +
                    "code=" + code +
                    ", text='" + text + '\'' +
                    '}';
        }

        public T getCode() {
            return code;
        }

        public String getText() {
            return text;
        }
    }
}
